package com.gt.quality.config.ai;

import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;

/**
 * 万里悲秋常作客,百年多病独登台
 *
 * @author : makeJava
 */
@Component
public class AiLocalConfig {

    HttpClient httpClient = HttpClient.create().
            // 设置连接超时时间为60秒
                    option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000).
            //  设置响应超时时间为60秒
                    responseTimeout(Duration.ofMillis(60000)).
            doOnConnected(con -> con.addHandlerLast(
                    // 设置读取超时时间为60秒
                    new ReadTimeoutHandler(60)
                    // 设置写入超时时间为60秒
            ).addHandlerLast(new WriteTimeoutHandler(60)));

    /**
     * 智普AI对话使用接口的处理器
     * 设置为 5MB缓冲区
     *
     * @param builder Builder
     * @return WebClient
     */
    @Bean(name = "useDialogue")
    public WebClient useDialogue(WebClient.Builder builder) {
        return builder
                .baseUrl("https://open.bigmodel.cn/api/paas/v4/chat/completions")
                // 设置为 5MB
                .codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(5 * 1024 * 1024))
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }
}
